package cn.ctodb.im.logic.rpc;

import cn.ctodb.im.dto.auth.AuthReqDTO;
import cn.ctodb.im.dto.auth.AuthRespDTO;
import cn.ctodb.im.dto.auth.LoginReqDTO;
import cn.ctodb.im.dto.auth.LoginRespDTO;
import cn.ctodb.im.logic.domain.User;
import cn.ctodb.im.logic.repository.UserRepository;
import cn.ctodb.im.rpc.AuthRpc;
import com.alibaba.dubbo.config.annotation.Service;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.UUID;

/**
 * All rights Reserved, Designed By www.ctodb.cn
 *
 * @version V1.0
 * @author: lichaohn@163.com
 * @date: 2018-11-09 9:55
 * @Copyright: 2018 www.ctodb.cn All rights reserved.
 */
@Service
public class AuthRpcImpl implements AuthRpc {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private static final String TOKEN_CACHE = "IM_TOKEN";

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public LoginRespDTO login(LoginReqDTO loginReqDTO) {
        LoginRespDTO loginRespDTO = new LoginRespDTO();
        try {
            User user = userRepository.findByCode(loginReqDTO.getUsername()).orElseThrow(() -> new RuntimeException("用户不存在"));
            String token = UUID.randomUUID().toString();
            getTokenCache().put(token, user.getId());
            loginRespDTO.setUid(user.getId());
            loginRespDTO.setToken(token);
        } catch (Exception e) {
            loginRespDTO.setFlag(false);
            loginRespDTO.setMsg(e.getMessage());
        }
        return loginRespDTO;
    }

    @Override
    public AuthRespDTO check(AuthReqDTO authReq) {
        logger.debug("接收消息{}", authReq);
        AuthRespDTO authRespDTO = new AuthRespDTO();
        try {
            String userId = getTokenCache().get(authReq.getToken());
            // TODO 测试用的代码需修改为对接单点登录
            if (StringUtils.isBlank(userId)) {
                throw new RuntimeException("验证失败");
            }
            authRespDTO.setStatus(AuthRespDTO.Status.OK);
        } catch (Exception e) {
            authRespDTO.setStatus(AuthRespDTO.Status.ERROR);
            authRespDTO.setErrMsg(e.getMessage());
        }
        return authRespDTO;
    }

    private BoundHashOperations<String, String, String> getTokenCache() {
        return redisTemplate.boundHashOps(TOKEN_CACHE);
    }
}
